export class Request {
  private config = {
    userId: 'aa7385b487e84f28a5e43e7574f4f0aa',
    deviceId: 'e20ca6dd21964f99a7d514bc4c1264e1',
  };
  private opt: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin',
  };
  private sendBeacon = navigator.sendBeacon
    ? (url: string, _data: any) => {
        const data = {
          ..._data,
          ...this.config,
        };
        if (data) navigator.sendBeacon(url, JSON.stringify(data));
      }
    : (url: string, data: any) => {
        // 传统方式传递参数
        const beacon = new Image();
        beacon.src = `${url}?v=${encodeURIComponent(JSON.stringify(data))}`;
      };
  private baseUrl = 'http://localhost:8081/';
  constructor() {}
  post(uri: string, data: object, useSendBeacon = true) {
    const url = this.baseUrl + uri;
    if (useSendBeacon) return this.sendBeacon(url, data);
    console.error("没有走sendBeacon")
    this.opt.method = 'POST';
    this.opt.body = JSON.stringify(data);
    return fetch(url, this.opt);
  }
}
